﻿using System;
using KeyCreation.Model;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;

namespace KeyCreation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Loading domain configuration section with name "Default".
            var domainConfiguration = DomainConfiguration.Load("Default");
            var domain = Domain.Build(domainConfiguration);

            int id;

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {

                    // Getting new key from key sequence for Person hierarchy
                    // Use this for obtaining keys for creating new entities
                    var key = Key.Generate<Person>(session);

                    Console.WriteLine("Generated key: {0}", key);

                    var person = new Person(session, key) {
                        Name = "John Smith"
                    };

                    id = person.Id;
                    t.Complete();
                }
            }

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {

                    // Creating key with that id and use it in query to fetch Person instance
                    // Use this for obtaining keys for existing entities
                    var key = Key.Create<Person>(domain, id);
                    
                    Console.WriteLine("Created key: {0}", key);

                    var person = session.Query.Single<Person>(key);

                    t.Complete();
                }
            }
        }
    }
}
